import { routes, routerMap } from '@/router/router'
import { authorization } from '@/api/user'
import { setToken } from '@/lib/util'

const state = {
  routers: routes,
  hasGetRules:　false
}

const mutations = {
  CONCAT_ROUTES (state, routerList) {
    state.routers = routerList.concat(routes)
    state.hasGetRules = true
    // console.log(state.routers)
  }
}

const getAccesRouterList = (routes, rules) => {
  return routes.filter(item => {
    if (rules[item.name]) {
      if (item.children) item.children = getAccesRouterList(item.children, rules)
      return true
    }
    else return false
  })
}

const actions = {
  authorization ({ commit }, token) {
    return new Promise((resolve, reject) => {
      authorization().then(res => {
        if (parseInt(res.code) === 401) reject(new Error('token error'))
        else {
          setToken(res.data.token)
          resolve(res.data.rules.page)
          // commit('SET_RULES', res.data.rules.component)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  concatRoutes ({ commit }, rules) {
    return new Promise((resolve, reject) => {
      try {
        let routerList = []
        if (Object.entries(rules).every(item => item[1])) routerList = routerMap  //  通过Object.entries()方法，将rules对象转换成二维数组，再用every()方法判断其中是否全部为true
        else routerList = getAccesRouterList(routerMap, rules)
        commit('CONCAT_ROUTES', routerList)
        resolve(routerList)
      } catch (error) {
        reject(error)
      }
    })
  }
}

export default {
  state,
  mutations,
  actions
}
